package org.dev.app.first.controller;

import org.apache.poi.util.IOUtils;
import org.dev.app.first.entity.Model;
import org.dev.app.first.poi.excel.exception.ExcelException;
import org.dev.app.first.poi.excel.parse.cache.poiutils.CacheExcelUtils;
import org.dev.app.first.poi.excel.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PoiExcelExportController {

	private static Logger logger = LoggerFactory.getLogger(PoiExcelExportController.class);

	public static final String exportPath = "D:\\backup\\";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@GetMapping(path = "/excel/export")
	@ResponseBody
	public void exportExcel(HttpServletResponse response) {
		System.out.println("***********************************exportExcel**********");

		Map<String, Object> result = new HashMap<String, Object>();

		result.put("error_no", "0");
		result.put("error_msg", "ok!");

		Model model = new Model("aaa1", "bbb", 123.234);

		List details = new ArrayList();
		details.add(new Model("user1", "kong", 1234.342));
		details.add(new Model("user2", "hello", 1224.342));
		details.add(new Model("user3", "world", 144.342));

		CacheExcelUtils.addValue("printDate", getCurrentDate("yyyy-MM-dd"));
		CacheExcelUtils.addValue("model", model);
		CacheExcelUtils.addValue("list", details);
		String config = "exceltemplates/demo.xlsx";

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(exportPath + "demo2.xlsx");
			CacheExcelUtils.export(config, fos);
		} catch (FileNotFoundException | ExcelException ex) {
			logger.error("{}", ex);
		} finally {
			IOUtils.closeQuietly(fos);
		}
		FileUtil.downloadFile(response, exportPath + "demo2.xlsx", "demo2.xlsx");
	}

	private static String getCurrentDate(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date());
	}
}
